package com.tusuo.stds.ui.complete;

import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import com.flyco.animation.BaseAnimatorSet;
import com.flyco.animation.FadeEnter.FadeEnter;
import com.flyco.animation.FadeExit.FadeExit;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.tusuo.stds.R;
import com.tusuo.stds.rest.LevelDetail;
import com.tusuo.stds.rest.Question;
import com.tusuo.stds.rest.RequestQuestionBean;
import com.tusuo.stds.ui.BaseToolbarActivity;
import com.tusuo.stds.ui.ToolbarOwner;
import com.tusuo.stds.ui.draft.DraftActivity_;
import com.tusuo.stds.ui.question.QuestionAdapterForQuestionBank;
import com.tusuo.stds.util.CustomViewPager;
import com.tusuo.stds.util.webview.WebViewManager;

import org.androidannotations.annotations.AfterInject;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.StringRes;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import myandroid.library.util.ApplicationHelper;
import rx.functions.Action0;

/**
 * Created by developer on 17-9-25.
 */

@EActivity(R.layout.activity_complete_question)
public class CompleteQuestionActivity extends BaseToolbarActivity<CompleteQuestionView,CompleteQuestionPresenter> implements CompleteQuestionView{

    public static final int QUESTION_TYPE_SINGLE = 1;
    public static final int QUESTION_TYPE_MULTI = 2;
    public static final int QUESTION_TYPE_TF = 3;
    public static final int QUESTION_TYPE_UNSURE = 7;

    @StringRes(R.string.question_type_single)
    String strTypeSingle;
    @StringRes(R.string.question_type_multi)
    String strTypeMulti;
    @StringRes(R.string.question_type_tf)
    String strTypeTF;
    @StringRes(R.string.question_type_unsure)
    String strTypeUnsure;
    @StringRes(R.string.question_pre_download)
    String strPreDownload;

    @ViewById(R.id.complete_question_tv_count)
    TextView tvCount;
    @ViewById(R.id.complete_question_tv_type)
    TextView tvType;
    @ViewById(R.id.complete_question_viewpager)
    CustomViewPager viewPager;

    private CompleteQuestionPresenter presenter;
    private int mDataId;
    private int mType;
    private int mCompleteId;
    private List<Question> mQuestionList;
    private String mSecretKey;
    private List<WebViewManager> mWebViewManagerList;
    private List<View> listView;
    private QuestionAdapterForQuestionBank adapter;
    private NormalDialog mDialog;
    private int currentIndex = -1;
    private int lastIndex = -1;
    private long lastTime = 0;
    private long currentTime = 0;
    private int mRecordId;


    @NonNull
    @Override
    public CompleteQuestionPresenter createPresenter() {
        presenter = new CompleteQuestionPresenter(this,mDataId,mType,mCompleteId);
        return presenter;
    }

    @AfterInject
    void init() {
        Intent intent = getIntent();
        if (intent != null && intent.getExtras() != null) {
            mDataId = intent.getIntExtra("dataId", -1);
            mType = intent.getIntExtra("type", -1);
            mCompleteId = intent.getIntExtra("completeId", -1);
        }
    }

    @AfterViews
    void initView() {
        setupUI(this);

        List<ToolbarOwner.MenuAction> menuActionList = new ArrayList<>();

        ToolbarOwner.MenuAction menuAction = new ToolbarOwner.MenuAction("草稿", new Action0() {
            @Override
            public void call() {
                startActivity(new Intent(CompleteQuestionActivity.this, DraftActivity_.class));
            }
        }, 0);

        menuActionList.add(menuAction);

        final ToolbarOwner.Config config = new ToolbarOwner.Config("强化训练", true, menuActionList);
        mToolbarOwner.setConfig(config);
        initDialog();

        mWebViewManagerList = new ArrayList<>();
        listView = new ArrayList<>();
    }

    private void initDialog() {
        BaseAnimatorSet bas_in = new FadeEnter();
        BaseAnimatorSet bas_out = new FadeExit();

        mDialog = new NormalDialog(this);
        mDialog.isTitleShow(false)
                .bgColor(Color.parseColor("#FFFFFF"))
                .cornerRadius(5)
                .content(getString(R.string.question_dlg_title))
                .contentGravity(Gravity.CENTER)
                .contentTextColor(Color.parseColor("#333333"))
                .dividerColor(Color.parseColor("#CCCCCC"))
                .btnText("点错了", "确认退出")
                .btnTextSize(15.5f, 15.5f)
                .btnTextColor(Color.parseColor("#0092FF"), Color.parseColor("#333333"))
                .widthScale(0.7f)
                .showAnim(bas_in)
                .dismissAnim(bas_out);

        mDialog.setOnBtnClickL(
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        mDialog.dismiss();
                    }
                },
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        mDialog.dismiss();
                        CompleteQuestionActivity.this.finish();
                    }
                }
        );
    }

    @Override
    public void initQuestion(List<Question> questionList, int id) {
        mQuestionList = questionList;
        mRecordId = id;
        for (int i = 0; i < mQuestionList.size(); i++) {
            View view = View.inflate(this, R.layout.item_question, null);
            BridgeWebView webView = (BridgeWebView) view.findViewById(R.id.item_question_webview);
            WebViewManager webViewManager = new WebViewManager(this, webView);

            Question question = mQuestionList.get(i);
            question.Text = question.getDecodedText(mSecretKey);
            question.QuestionAnalysis = question.getDecodedQuestionAnalysis(mSecretKey);
            for (Question.QuestionOption option : question.QuestionOptionList) {
                option.Content = option.getDecodedContent(mSecretKey);
            }

            listView.add(view);
            mWebViewManagerList.add(webViewManager);
        }

        LevelDetail levelDetail = new LevelDetail();
        levelDetail.QuestionList = questionList;
        adapter = new QuestionAdapterForQuestionBank(listView,levelDetail,mWebViewManagerList,mSecretKey,this);
        viewPager.setOffscreenPageLimit(0);
        viewPager.setAdapter(adapter);
        viewPager.setCurrentItem(0);
        viewPager.enableRightSwipe(false);
        viewPager.enableLeftSwipe(false);

        ApplicationHelper.getInstance().addActivity(this);
        initText(mQuestionList.get(0),0);

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {
                if (state == CustomViewPager.SCROLL_STATE_IDLE) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            int curIndex = viewPager.getCurrentItem();

                            if (curIndex != currentIndex) {
                                currentIndex = curIndex;
                                lastTime = System.currentTimeMillis();
                            }

                            if (curIndex != lastIndex && lastIndex != -1) {
                                viewPager.enableRightSwipe(true);
                                viewPager.enableLeftSwipe(true);
                            }else {
                                viewPager.enableLeftSwipe(true);
                                viewPager.enableRightSwipe(false);
                            }

                            final Question curQuestion = mQuestionList.get(curIndex);
                            initText(curQuestion,curIndex);
                        }
                    });

                }
            }
        });


    }

    @Override
    public void setSecretKey(String secretKey) {
        mSecretKey = secretKey;
    }

    @Override
    public void requestSubmitQuestion(int questionId, long elapseSec, boolean isFinal, String answerContent) {
        RequestQuestionBean bean = new RequestQuestionBean();
        bean.questionId = questionId;
        bean.elapseSec = elapseSec;
        bean.answerContent = answerContent;
        bean.isFinal = isFinal;
        Message msg = new Message();
        msg.what = 321;
        msg.obj = bean;
        handler.sendMessageDelayed(msg,3000);
    }

    @Override
    public void toNextQuestion() {
        handler.sendEmptyMessageDelayed(123,1000);
    }

    @Override
    public void toResultActivity() {
        Intent intent = new Intent();
        intent.setClass(this,CompleteResultActivity_.class);
        intent.putExtra("id",mRecordId);
        startActivity(intent);
        finish();
    }

    public void initText(Question question,int index) {
        switch (question.QuestionType) {
            case QUESTION_TYPE_SINGLE:
                tvType.setText(strTypeSingle);
                break;
            case QUESTION_TYPE_MULTI:
                tvType.setText(strTypeMulti);
                break;
            case QUESTION_TYPE_TF:
                tvType.setText(strTypeTF);
                break;
            case QUESTION_TYPE_UNSURE:
                tvType.setText(strTypeUnsure);
                break;
            default:
                tvType.setText("未知");
                break;
        }
        tvCount.setText(getString(R.string.question_count, index + 1, mQuestionList.size()));
    }

    public void setLastTime() {
        if (viewPager.getCurrentItem() == 0) {
            lastTime = System.currentTimeMillis();
        }
    }

    @Override
    protected void onDestroy() {
        if (mDialog != null) {
            mDialog.superDismiss();
            mDialog = null;
        }

        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        showTipDialog();
    }

    public void showTipDialog() {
        mDialog.show();
    }

   public BridgeHandler mSubmitAnswerHandler = new BridgeHandler() {
        @Override
        public void handler(String json, CallBackFunction function) {
            try {
                String answerContent = new JSONObject(json).getString("AnswerContent");
                if (!TextUtils.isEmpty(answerContent)) {
                    int curIndex = viewPager.getCurrentItem();
                    boolean isFinal = false;
                    if (curIndex == mQuestionList.size() - 1) {
                        isFinal = true;
                    }
                    currentTime = System.currentTimeMillis();
                    long elapseSec = (currentTime - lastTime) / 1000;
                    adapter.setAnswerContent(viewPager.getCurrentItem(),answerContent);
                    presenter.submitAnswer(answerContent,mQuestionList.get(curIndex).Id,elapseSec,isFinal);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            if (msg.what == 123) {
                int currentItem = viewPager.getCurrentItem();

                if (currentItem != mQuestionList.size() - 1) {
                    viewPager.setCurrentItem(currentItem + 1);
                    adapter.setAnswerContentReviewMode(currentItem);
                    lastIndex = currentItem + 1;
                    viewPager.enableLeftSwipe(true);
                    viewPager.enableRightSwipe(false);
                }
            }else if (msg.what == 321) {
                RequestQuestionBean bean = (RequestQuestionBean) msg.obj;
                presenter.submitAnswer(bean.answerContent, bean.questionId, bean.elapseSec, bean.isFinal);
            }
        }
    };

}
